﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using FlexnetConsultants.CookieNotification.Settings;
using Microsoft.SharePoint.Utilities;
using FlexnetConsultants.CookieNotification.Code;

namespace FlexnetConsultants.CookieNotification
{
    public partial class CookieSettingsPage : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lblVersion.Text = Globals.CurrentVersion;     
                LoadSettings();
            }

        }

        protected void OKButton_Click(object sender, EventArgs e)
        {
            SaveSettings();
        }

        private void Redirect()
        {
            SPUtility.Redirect(
                    SPUtility.GetServerRelativeUrlFromPrefixedUrl("~site/generalapplicationsettings.aspx"),
                    SPRedirectFlags.Default, 
                    this.Context);
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            Redirect();
        }

        private void SaveSettings()
        {
            try
            {
                FCCookieNotificationSettings settings = FCCookieNotificationSettings.Local;

                settings.CookieName = txtCookieName.Text;
                settings.CookieMessageTitle = txtCookieMessageTitle.Text;
                settings.CookieMessageBody = txtCookieMessageBody.Text;
                settings.AcceptCookieLinkTitle = txtAcceptCookieLinkTitle.Text;
                settings.Enabled = chkEnabled.Checked;
               
                settings.DebugMode = chkDebugMode.Checked;
                

                settings.Update();
                litPageWarning.Text = "Settings updated!";

                Redirect();
            }
            catch (Exception ex)
            {
                litPageWarning.Text = "Error while updating settings: " + ex.Message;
            }

        }

        private void LoadSettings()
        {

            FCCookieNotificationSettings settings = FCCookieNotificationSettings.Local;

            if (string.IsNullOrEmpty(settings.CookieName))
                txtCookieName.Text="FCCookieAccept";
            else
                txtCookieName.Text=settings.CookieName;

            txtCookieMessageTitle.Text=settings.CookieMessageTitle;
            txtCookieMessageBody.Text = settings.CookieMessageBody;
            txtAcceptCookieLinkTitle.Text = settings.AcceptCookieLinkTitle;
            chkEnabled.Checked=settings.Enabled ;
            chkDebugMode.Checked=settings.DebugMode;

        }

    }
}
